package org.kazuhiko.rpg.server.net;

import java.net.SocketAddress;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.kazuhiko.rpg.server.io.PersistenceManager;
import org.kazuhiko.rpg.server.model.Player;
import org.kazuhiko.rpg.server.net.packet.Packet;
import org.kazuhiko.rpg.server.net.packet.PacketManager;
import org.kazuhiko.rpg.server.net.packet.handler.PacketHandlerManager;

public class RPGSession extends Connectable
{
	//private final static Logger logger = LoggerFactory.getLogger( RPGSession.class );
	
	private final IoSession session;
	
	private final ActionSender actionSender = new ActionSender( this );

	private PacketHandlerManager<?> handler;
	
	private PacketManager packets;
	
	private Player player;
	
	public RPGSession( IoSession session )
	{
		this.session = session;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PacketHandlerManager getHandler()
	{
		if( handler == null )
		{
			handler = new PacketHandlerManager( ( Map<Integer, String> ) PersistenceManager.getPersistenceManager().load( "data/packetHandlers.xml" ) );
		}
		
		return handler;
	}
	
	public PacketManager getPackets()
	{
		if( packets == null )
		{
			packets = ( PacketManager ) PersistenceManager.getPersistenceManager().load( "data/packets.xml" );
		}
		
		return packets;
	}
	
	public ActionSender getActionSender()
	{
		return actionSender;
	}
	
	public Player getPlayer()
	{
		return player;
	}
	
	public void setPlayer( Player player )
	{
		this.player = player;
	}
	
	@SuppressWarnings("unchecked")
	public void handle( Packet packet )
	{
		getHandler().handlePacket( this, packet );
	}
	
	public SocketAddress getAddress()
	{
		return session.getRemoteAddress();
	}
	
	public void send( Packet packet )
	{
		send( packet, session );
	}
	
	public void close()
	{
		session.close( false );
	}
	
	public void setReady()
	{
		state = State.READY;
	}
	
	public boolean isAuthenticated()
	{
		return ( player != null ) ? true : false;
	}
}
